package controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import model.Subject;
import model.SubjectMsg;
import model.User;
import service.ShoppingcartService;
import service.SubjectService;
import service.UserService;
import service.impl.ShoppingcartServiceImpl;
import service.impl.SubjectServiceImpl;
import service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/shoppingcart")
public class ShoppingCartServlet extends HttpServlet {
    SubjectService subjectService = new SubjectServiceImpl();
    ShoppingcartService shoppingcartService = new ShoppingcartServiceImpl();
    UserService userService=new UserServiceImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置字符格式
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");

        //以字符流的形式接收数据
        BufferedReader reader = new BufferedReader(req.getReader());
        StringBuilder json = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            json.append(line);
        }
        //将接收的数据转换为json对象方便后面获取
        JSONObject jsonObject = JSON.parseObject(json.toString());

        //创建一个用来传数据的JSON对象
        JSONObject message = new JSONObject();

        //获取用户购物车
        int pageIndex = jsonObject.getInteger("pageIndex");
        int pageSize=3;
        long uid = jsonObject.getLong("uid");
        List<Long> list = shoppingcartService.getSubject(uid, pageIndex, pageSize);
        List<SubjectMsg> subjectMsgList =new ArrayList<>();

        for( Long i:list) {
            SubjectMsg subjectMsg=new SubjectMsg();
            Subject subject=subjectService.get(i);
            subjectMsg.setSubject(subject);
            subjectMsg.setUser(userService.findById(subject.getUid()));
            subjectMsgList.add(subjectMsg);
        }
        int count=shoppingcartService.countById(uid);

        message.put("subjectMsg", subjectMsgList);
        message.put("pageCount", count % pageSize != 0 ? count / pageSize + 1 : count / pageSize);
        resp.getWriter().write(message.toString());
    }
}